<template>
  <el-card shadow="hover" class="mt-20">
    <el-form>
      <el-form-item label="属性名">
        <el-input
          placeholder="请输入属性名"
          class="attr-input"
          v-model.trim="attrFormData.attrName"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <!-- 
          按钮禁用效果
            attrName 有值 不禁用
            attrName 没值 禁用
        -->
        <el-button
          type="primary"
          :disabled="!attrFormData.attrName"
          @click="showAddAttrValue"
        >
          添加属性值
        </el-button>
        <el-table :data="attrFormData.attrValueList" border class="mt-20">
          <el-table-column
            label="序号"
            type="index"
            width="60"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <!-- 
                显示模式和编辑模式切换
               -->
              <el-input
                placeholder="请输入属性值"
                size="small"
                ref="inputRef"
                v-model="row.valueName"
                v-if="row.isShowEdit"
                @blur="switchShow(row, $index)"
              ></el-input>

              <div v-else @click="switchEdit(row)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template v-slot="{ row, $index }">
              <el-popconfirm
                :title="`您确认要删除 ${row.valueName} 吗?`"
                @confirm="delAttrValue($index)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    :icon="Delete"
                    size="small"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <!-- 
          当属性名有值 并且 至少有一个属性值 才能使用保存 - 按钮不禁用  
            属性名有值 attrFormData.attrName
            至少有一个属性值(至少有一条数据，并且每条数据都要有属性值)
              attrFormData.attrValueList.length > 0
              attrFormData.attrValueList.every(attrValue => attrValue.valueName)
          反之 按钮禁用
         -->
        <el-button type="primary" :disabled="saveBtnDisabled" @click="addAttr">
          保存
        </el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick, computed } from "vue";
import { Delete } from "@element-plus/icons-vue";
import { addOrUpdateAttrApi } from "@/api/product/attr";
import type { AttrItem, AttrValueItem } from "@/api/product/models/attrModels";
import { useCategoryStore } from "@/stores/category";
import { useAttrStore } from "@/stores/attr";

defineOptions({
  name: "AddOrUpdateAttr",
});

const categoryStore = useCategoryStore();

// 添加或修改属性
const addAttr = async () => {
  await addOrUpdateAttrApi({
    id: attrStore.id, // 添加id是undefined，等于没写。修改id有值
    ...attrFormData,
    categoryId: categoryStore.category3Id,
    categoryLevel: 3,
  });
  ElMessage.success(`${attrStore.id ? "修改" : "添加"}属性成功`);
  cancel();
};

const saveBtnDisabled = computed(() => {
  return !(
    attrFormData.attrName &&
    attrFormData.attrValueList.length > 0 &&
    attrFormData.attrValueList.every((attrValue) => attrValue.valueName)
  );
});

// 删除属性值
const delAttrValue = (index: number) => {
  attrFormData.attrValueList.splice(index, 1);
};

// 编辑模式切换到显示模式
const switchShow = (row: AttrValueItem, index: number) => {
  if (!row.valueName) {
    // 删除整行数据
    attrFormData.attrValueList.splice(index, 1);
    return;
  }
  row.isShowEdit = false;
};
// 显示模式切换到编辑模式
const switchEdit = async (row: AttrValueItem) => {
  row.isShowEdit = true;
  await nextTick();
  // 让 input 获取焦点
  inputRef.value.focus();
};

// 3. 添加属性值
const inputRef = ref();

const showAddAttrValue = async () => {
  // 给数组添加一个对象，表格就会渲染一行数据
  attrFormData.attrValueList.push({
    valueName: "", // 必选属性，必须给
    // 添加一个标识，代表显示和编辑模式切换
    isShowEdit: true,
  });
  // nextTick(() => {
  //   // 让 input 获取焦点
  //   inputRef.value.focus();
  // });
  /*
    简单理解：等用户界面更新完毕，在触发指定回调（返回promise状态变化为成功状态）
    真正理解：将回调函数(要想执行的操作)添加到异步队列中
  */
  await nextTick();

  // 让 input 获取焦点
  inputRef.value.focus();
};

// 2. 表单数据
const attrStore = useAttrStore();

const attrFormData = reactive<AttrItem>({
  // 表单数据数据名称要和将来发送请求的接口参数名称一致
  attrName: attrStore.attrName,
  attrValueList: attrStore.attrValueList,
});

// 1. 取消
const emit = defineEmits(["setIsShowAttrList"]);

const cancel = () => {
  emit("setIsShowAttrList", true);
};
</script>

<style scoped lang="scss">
.attr-input {
  width: 250px;
}
</style>
